package com.web;
import com.alibaba.druid.support.json.JSONUtils;
import com.entity.CatPost;
import com.entity.Knowledge;
import com.entity.User;
import com.entity.Varietiess;
import com.service.UserService;
import com.service.dwm.CatPostService;
import com.service.dwm.VarietiesService;
import com.service.lqj.KnowledgeService;
import com.service.xbq.HeadService;
import com.utils.EncryptCodeUtils;
import com.utils.WebUtils;
import com.web.lqj.UserService_lqj;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/catlogin")
@MultipartConfig
public class CatLoginServlet extends HttpServlet {

    private UserService_lqj userService_lqj = new UserService_lqj();

    private KnowledgeService knowledgeService = new KnowledgeService();
    private VarietiesService varietiesService = new VarietiesService();
    private CatPostService catPostService = new CatPostService();
    //request对象
    private HttpServletRequest request;
    //response对象
    private HttpServletResponse response;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //初始化请求和响应
        this.request = request;
        this.response = response;
        String method = request.getParameter("method");
        if (method == null){
            request.getRequestDispatcher("jsp/hs/index.jsp").forward(request,response);
        }
        switch (method) {
            case "login": login(); break;
            case "logOut": logOut(); break;
            case "toLoginPage": toLoginPage(); break;
            case "toRegPage": toRegPage(); break;
            case "reg": regUser(); break;
            case "checkUsername": checkUsername(); break;
            case "index": showIndex(); break;
            case "indexSell": showSell(); break;



        }
    }

    private void showSell() throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        CatPost catPost = catPostService.queryCatPost(id);
        request.setAttribute("catPost",catPost);
        WebUtils.toRequestPageVarietiess(request, response, "sell");
    }

    /**
     * 跳转到登陆界面
     */
    private void toLoginPage() throws ServletException, IOException {
     //WebUtils.toRequestPage(request, response, "login");
        request.getRequestDispatcher("jsp/lqj/catlogin.jsp").forward(request,response);
    }

    /**
     * 跳转到注册页面
     */
    private void toRegPage() throws ServletException, IOException {
      // WebUtils.toRequestPage(request, response, "post");
        request.getRequestDispatcher("jsp/lqj/post.jsp").forward(request,response);
    }

    /**
     * 登出
     */
    private void logOut() throws IOException {
        //获取当前的session
        HttpSession session = request.getSession();
        //session.invalidate();//清空，销毁session
        session.removeAttribute("user");
        session.setAttribute("msg","注销成功，请重新登录");
        response.sendRedirect("login?method=toRegPage");
    }

    private void showIndex() {

    }

    /**
     * 核对用户名是否已存在
     */
    private void checkUsername() {
        String username = request.getParameter("username");
        User user = userService_lqj.queryUserByUsername(username);
        System.out.println("checkUsername:"+user);
        WebUtils.sendMSG(response, (user==null)?"1":"-1");
    }

    /**
     * 注册用户
     */
    private void regUser() throws IOException, ServletException {
        //获取当前的session
        HttpSession session = request.getSession();
        //正式注册
        User user = WebUtils.getBean(User.class, request);

        //设置盐值
        user.setPhone(WebUtils.getRandomString());
        //重新设置密码
        user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),
                user.getPhone()));

        //重新设置文件路径
        //user.setPic(WebUtils.uploadFile(request, "pic"));
        user.setPic(null);

        //插入数据
        boolean result = userService_lqj.addUser(user);
        System.out.println(result);
        //增加完成之后，跳转到首页
        session.setAttribute("title","注册提醒");
        session.setAttribute("msg",result?"注册成功":"注册失败");
        session.setAttribute("booleans", result?"true":"false");
        //跳转登陆页面
        if(result) {
            response.sendRedirect("catlogin?method=toLoginPage");
        }else {
            response.sendRedirect("catlogin?method=toLoginPage");
        }
    }

    /**
     * 用户登陆
     */
    private void login() throws IOException {
        //获取当前的session
        HttpSession session = request.getSession();
        //前端传递过来的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+","+password);
        //通过用户名查询数据库的数据
        User user = userService_lqj.queryUserByUsername(username);
     //   System.out.println(user);
        String msg = "";
        if (user == null) {

        } else {
            //先把传递过来的密码加密一遍
            String encryptPwd = EncryptCodeUtils.getEncryptStr(password, user.getPhone());
            if (user.getPassword().equals(encryptPwd)) {

                //管理员
                if (user.getAdministrators().equals("T")){
                    try {
                        msg = "登陆成功";
                        System.out.println("管理员");
                        session.setAttribute("msg", msg);
                        session.setAttribute("flag", true);
                        session.setAttribute("user", user);
                        HeadService headService = new HeadService();
                        int i = headService.queryUserpost(username);
                        session.setAttribute("postNum",i);
                        request.getRequestDispatcher("user?method=index").forward(request,response);
                    } catch (ServletException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                //超级管理员
                if (user.getSupertube().equals("T")){
                    try {
                        System.out.println("超级理由");
                        msg = "登陆成功";
                        session.setAttribute("msg", msg);
                        session.setAttribute("flag", true);
                        session.setAttribute("user", user);
                        HeadService headService = new HeadService();
                        int i = headService.queryUserpost(username);
                        session.setAttribute("postNum",i);
                        request.getRequestDispatcher("user?method=indexVIP").forward(request,response);
                    } catch (ServletException e) {
                        e.printStackTrace();
                    }
                    return;
                }

                msg = "登陆成功";
                 HeadService headService = new HeadService();
                int i = headService.queryUserpost(username);
                session.setAttribute("postNum",i);
                session.setAttribute("msg", msg);
                session.setAttribute("flag", true);
                session.setAttribute("user", user);
                //多长时间没有操作页面就T出去
                //session.setMaxInactiveInterval(3*60);
                //清空
                //session.invalidate();
                //移除
                //session.removeAttribute("house");
                //直接到首页
                try {
                    List<Knowledge> knowledges = knowledgeService.queryKnowledges();
                    request.getSession().setAttribute("knowledge", knowledges);
                    List<Varietiess> varieties = varietiesService.queryVarietiess();
                    request.getSession().setAttribute("varieties", varieties);
                    List<CatPost> catPosts1 = catPostService.queryCatPostsCatbreed1();
                    List<CatPost> catPosts2 = catPostService.queryCatPostsCatbreed2();
                    List<CatPost> catPosts3 = catPostService.queryCatPostsCatbreed3();
                    List<CatPost> catPosts4 = catPostService.queryCatPostsCatbreed4();
                    List<CatPost> catPosts5 = catPostService.queryCatPostsCatbreed5();
                    List<CatPost> catPosts6 = catPostService.queryCatPostsCatbreed6();
                    List<CatPost> catPosts7 = catPostService.queryCatPostsCatbreed7();

                    request.getSession().setAttribute("catPosts1", catPosts1);
                    request.getSession().setAttribute("catPosts2", catPosts2);
                    request.getSession().setAttribute("catPosts3", catPosts3);
                    request.getSession().setAttribute("catPosts4", catPosts4);
                    request.getSession().setAttribute("catPosts5", catPosts5);
                    request.getSession().setAttribute("catPosts6", catPosts6);
                    request.getSession().setAttribute("catPosts7", catPosts7);
                    request.getRequestDispatcher("jsp/hs/index.jsp").forward(request,response);
                } catch (ServletException e) {
                    e.printStackTrace();
                }
                return;
            } else {
                msg = "密码错误！！！";
            }
        }
        session.setAttribute("title","登录提醒");
        session.setAttribute("msg", "用户名或密码错误");
        session.setAttribute("booleans","true");
        response.sendRedirect("catlogin?method=toLoginPage");

    }
}
